package com.lanxiao.cloud.common.redis.config;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * @author ：qiaoliang
 * @date ：2021-10-15
 */
public class KeyStringRedisSerializer  implements RedisSerializer<String> {

  private final Charset charset;
  private final String keys;
  public static final StringRedisSerializer US_ASCII;
  public static final StringRedisSerializer ISO_8859_1;
  public static final StringRedisSerializer UTF_8;

  public KeyStringRedisSerializer(String keys) {
    this(StandardCharsets.UTF_8, keys);
  }

  public KeyStringRedisSerializer(Charset charset, String keys) {
    Assert.notNull(charset, "Charset must not be null!");
    this.keys = keys + ":";
    this.charset = charset;
  }

  @Override
  public String deserialize(@Nullable byte[] bytes) {
    return bytes == null ? null : new String(bytes, this.charset).replaceFirst(keys, "");
  }

  @Override
  public byte[] serialize(@Nullable String string) {
    return string == null ? null : (keys + string).getBytes(this.charset);
  }

  @Override
  public Class<?> getTargetType() {
    return String.class;
  }

  static {
    US_ASCII = new StringRedisSerializer(StandardCharsets.US_ASCII);
    ISO_8859_1 = new StringRedisSerializer(StandardCharsets.ISO_8859_1);
    UTF_8 = new StringRedisSerializer(StandardCharsets.UTF_8);
  }

}
